<template>
  <div class="chat-footer">
    <div class="chat-footer-tools">
      <!-- 表情发送 -->
      <Emoji
        style="margin-right: 14px"
        ref="commonEmoji"
        mode="im"
        @setEmoji="setEmoji"
      />
      <!-- 上传图片 -->
      <UploadImage style="margin-right: 14px" />
      <!-- 上传文件 -->
      <UploadFile style="margin-right: 14px" />
    </div>

    <!-- 消息输入框 -->
    <div class="chat-footer-textarea footer-send-input">
      <Editor
        mode="simple"
        style="height: 100%; width: 100%; overflow-y: hidden"
        :default-config="editorConfig"
        v-model="message"
        @onChange="onChange"
        @onCreated="onCreated"
        @customPaste="customPaste"
      />
    </div>

    <div class="chat-footer-send">
      <div class="explain-text">{{$t('im.imChat.components.messageBox.inputEdit.des1')}}</div>
      <base-button type="primary" :disabled="isEmpty" @event="onSendTextMsg">
        {{$t('common.base.send')}}
      </base-button>
    </div>
  </div>
</template>

<script>
/** vue */
import Emoji from '@src/component/emoji';
import UploadImage from '@src/modules/system/frame/component/InternalCoordination/chat/components/upload/UploadImage';
import UploadFile from '@src/modules/system/frame/component/InternalCoordination/chat/components/upload/UploadFile';
/** util */
import i18n from '@src/locales';
import { difference } from 'lodash';
import { sendSingleMessage } from '@src/modules/system/frame/component/InternalCoordination/chat/components/send.js';
import { deleteServerFiles } from 'pub-bbx-utils';
import {
  getCustomPasteValue,
  uploadFile as EditorUploadFile,
  isImageNode,
  checkValIsEmpty,
  getMessageType,
} from 'src/modules/im/imChat/components/messageBox/inputEdit/util.js';
import Log from '@src/util/log'
/** components */
import { Editor } from '@wangeditor/editor-for-vue';
import { DomEditor } from '@wangeditor/editor';

export default {
  name: 'ChatFooter',
  inject: ['chatParams'],
  data() {
    return {
      message: '', // 输入框的值
      editor: null,
      isEmpty: true,
      editorConfig: {
        placeholder: i18n.t('im.imChat.components.messageBox.inputEdit.pla1'),
        pasteFilterStyle: false,
        selection: null,
        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
          uploadImage: {
            customBrowseAndUpload() {
              // 自定义上传图片
            },
          },
        },
        hoverbarKeys: {
          link: {
            menuKeys: [],
          },
          text: {
            menuKeys: [],
          },
          image: {
            menuKeys: [],
          },
        },
      },
      fileInfo: {},
      oldContent: {
        oldImages: [],
      },
      canDelete: true,
    };
  },
  computed: {
    errorChat() {
      return this.chatParams()?.errorChat
    }
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
      if (this.disabled) this.editor.disable();
      const { $textArea } = DomEditor.getTextarea(editor);

      // 监听shift+ctrl按键
      if ($textArea) {
        $textArea.on('keydown', event => {
          if (event.key === 'Enter' && event.ctrlKey) {
            this.dangerouslyInsertHtml('<span><br /></span>');
            event.preventDefault();
          }
        });

        // 监听Enter按键
        $textArea.on('keypress', event => {
          if (event.key === 'Enter') {
            this.onSendTextMsg();
            event.preventDefault();
          }
        });

        // 监听双击事件
        $textArea.on('dblclick', event => {
          let target = event.target;
          if (isImageNode(target)) {
            let dataHref = target.getAttribute('data-href');
            dataHref = dataHref ? JSON.parse(dataHref) : dataHref;
            if (dataHref?.isemoji) return;
            this.$previewElementImg(target.currentSrc);
            event.preventDefault();
          }
        });

        // 监听删除按键
        $textArea.on('keypress', event => {
          if (event.keyCode == 8 || event.keyCode == 46) {
            setTimeout(() => {
              // 解决连续多张图片排列，删除后面一张图片会默认选中前面一张图片的问题
              this.editor.move(1);
            });
          }
        });
      }
    },
    onChange(editor) {
      this.isEmpty = checkValIsEmpty(editor.children);
      this.diffContent()
    },
    // 粘贴事件
    async customPaste(editor, e, callBack) {
      e.preventDefault()
      callBack(false)
      let res = getCustomPasteValue(e);
      if (!res) return;

      if (res.type == 'text') {
        this.insertText(res.value);
      } else if (res.type == 'file' && res.fileType == 'image') {
        const fileInfo = await EditorUploadFile(res.value);
        if (!fileInfo) return;
        this.fileInfo = fileInfo;
        const { id, ossUrl } = fileInfo;
        this.dangerouslyInsertHtml(`<img src="${ossUrl}" alt="${id}"/>`);
      }
    },
    dangerouslyInsertHtml(val) {
      this.editor.dangerouslyInsertHtml(val);
    },
    insertText(val) {
      this.editor.insertText(val);
    },
    // 比较内容
    diffContent() {
      try {
        const { oldImages } = this.oldContent
        const images = this.editor.getElemsByType('image')

        // 比较图片，判断是否有被删除
        {
          const diffImagesIds = difference(oldImages.map(v=>v.alt), images.map(v=>v.alt))
          if (diffImagesIds.length && this.canDelete) {
            deleteServerFiles(diffImagesIds)
          } else {
            this.canDelete = true
          }
        }
        
        // 更新旧值
        this.oldContent = {
          oldImages: images
        }
      } catch (error) {
        Log.error(error)
      }
    },
    /** 获取表情选中的值 */
    setEmoji(txt){
      this.$nextTick(()=>{
        this.getFocus()
        this.insertText(txt)
      })
    },
    getFocus() {
      this.editor.focus();
    },
    /** 发送消息 */
    async onSendTextMsg() {
      if (this.isEmpty) return;

      this.editor.disable();
      const messageType = getMessageType(this.editor.children);
      try {
        const params = {
          chatType: this.chatParams()?.chatType,
          chatUuid: this.chatParams()?.chatUuid,
          messageType: '',
          messageContent: {},
        };
       
        if (messageType == 'txt') {
          params.messageType = 'text'
          params.messageContent = {
            msg: this.editor.getText().replace(/^\s+|\s+$/g, ''),
          };
        } else if (messageType == 'newImage') {
          params.messageType = 'image'
          params.messageContent = {
            type: 'image',
            fileName: this.fileInfo.fileName,
            fileSize: this.fileInfo.size,
            url: this.fileInfo.ossUrl,
            fileId: this.fileInfo.id
          };
        } else if (messageType == 'paragraph') {
          params.messageType = 'paragraph'
          if(this.isWeChat) return this.$message.warning(this.$t('im.imChat.components.messageBox.inputEdit.tips1'))
          params.messageContent = { 
            msg: this.editor.getHtml(),
            nodes: this.editor.children,
          };
        }
        let messageInfo = await sendSingleMessage(params);
        this.$eventBus.$emit('addMsg_insideIM', messageInfo)
        this.$eventBus.$emit('updateCurrentChat', messageInfo)
        this.message = '';
        this.canDelete = false;
        this.editor.clear();
      } catch (err) {
        Log.error(err)
      } finally {
        this.editor.enable();
      }
      this.message = '';
    },
    /** 输入框获取焦点 */
    onFocus() {
      this.$refs.replyInput.$el.querySelector('textarea').focus();
    },
    /** 监听enter按键 */
    keyDown(e) {
      e.preventDefault();
    },
    keyUp(e) {
      if (e.ctrlKey && e.keyCode == 13) {
        // 用户点击了ctrl+enter触发
        this.message += '\n';
      } else if (e.keyCode == 13 || e.type == 'click') {
        if (this.message.trim() == '') {
          this.message = '';
          return;
        }
        e.preventDefault();
        this.onSendTextMsg();
      }
    },
  },
  components: {
    Emoji,
    UploadImage,
    UploadFile,
    Editor,
  },
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
::v-deep .w-e-text-placeholder {
  top: 6px !important;
  left: 5px !important;
  font-style: inherit !important;
}
::v-deep .w-e-text-container [data-slate-editor] {
  padding: 0 !important;
}
::v-deep .w-e-text-container [data-slate-editor] p {
  margin: 4px 0 !important;
  padding-left: 4px !important;
}
::v-deep .w-e-image-container img {
  vertical-align: bottom;
  width: 100% !important;
  height: auto !important;
  max-width: 150px !important;
}
::v-deep .w-e-image-dragger {
  // 隐藏图片推拽
  display: none;
}
::v-deep .w-e-selected-image-container {
  // 图片点击选中
  border: 1px solid #b4d5ff !important;
  padding: 1px !important;
  overflow: inherit !important;
}
::v-deep .w-e-image-container:hover {
  // 图片hover
  box-shadow: none !important;
}
</style>
<style scoped lang="scss">
.chat-footer {
  width: 100%;
  height: 150px;
  border-top: 1px solid #e8e8e8;
  box-sizing: border-box;
  padding: 12px;
  display: flex;
  flex-direction: column;
  &-tools {
    width: 100%;
    position: relative;
    display: flex;
    align-items: center;
    flex-shrink: 0;
    .common-emoji {
      position: relative;
      z-index: 9999;
      transform: inherit;
      top: 0;
      left: 0;
    }
  }
  &-textarea {
    flex: 1;
  }

  &-send {
    height: 32px;
    display: flex;
    justify-content: right;
    align-items: center;
    flex-shrink: 0;
    .explain-text {
      color: #bfbfbf;
      font-size: 10px;
      line-height: 32px;
      margin-right: 8px;
    }
  }
}
::v-deep .el-textarea__inner {
  border: none;
  background: #fff !important;
  padding-left: 0;
}
</style>
<style lang="scss" scoped>
.footer-send-input {
  flex: 1;
  max-width: 100%;
  overflow-y: auto;
  word-break: break-all;
  display: flex;
  flex-direction: column;
  .send-btn {
    display: flex;
    justify-content: flex-end;
    margin-top: 6px;
    .explain-text {
      font-size: 10px;
      color: #bfbfbf;
      line-height: 32px;
      margin-right: 8px;
    }
  }
}
</style>
